package com.jzlw.huozhuduan.base;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.blankj.utilcode.util.ToastUtils;
import com.jzlw.huozhuduan.R;
import com.jzlw.huozhuduan.dialog.MainDialog;
import com.jzlw.huozhuduan.dialog.MyPhotoDialog;
import com.jzlw.huozhuduan.dialog.MyWalletDialog;
import com.jzlw.huozhuduan.dialog.ShowDialog;
import com.jzlw.huozhuduan.skeleton.Skeleton;
import com.jzlw.huozhuduan.skeleton.ViewSkeletonScreen;


import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;


/**
 * ClassName BaseLazyFragment
 * Description 懒加载Fragment
 */
public abstract class BaseLazyFragment extends Fragment {

    protected boolean isVisible;
    private boolean isPrepared;
    private boolean isFirst = true;
    public View rootView;
    public LayoutInflater mInflater;
    public Context mContext;
    protected MainDialog mainDialog;
    private ViewSkeletonScreen mLoading;
    private OnRetryListener onRetryListener;
    public MyWalletDialog walletDialog;
    private ShowDialog showDialog;
    private MyPhotoDialog myPhotoDialog;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isPrepared = true;
        initPrepare();
        mainDialog = new MainDialog(getActivity());
        if (isRegisterEventBus()) {
            if (!EventBus.getDefault().isRegistered(this))
                EventBus.getDefault().register(this);
        }
    }

    @Override
    public View onCreateView(@Nullable LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//        getActivity().requestWindowFeature(Window.FEATURE_NO_TITLE);
        if (rootView == null) {
            mInflater = inflater;
            mContext = inflater.getContext();

            rootView = mInflater.inflate(getRootViewId(), container, false);
            ButterKnife.bind(this, rootView);
        }
        return rootView;
    }
    public void setPhotoDialog(View.OnClickListener photoOnClickListener,View.OnClickListener albumOnClickListener ){
        myPhotoDialog = new MyPhotoDialog(mContext);
        myPhotoDialog.setPhotoDialog(photoOnClickListener,albumOnClickListener);
        myPhotoDialog.setCanceledOnTouchOutside(false);
        myPhotoDialog.show();

    }
    public void setShowDialog(String tit,String msg,View.OnClickListener onClick){
        showDialog = new ShowDialog(mContext);
        showDialog.setShowDialog(tit,msg,onClick);
        showDialog.setCanceledOnTouchOutside(false);
        showDialog.show();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisible = true;
            lazyLoad();//
        } else {
            isVisible = false;
            onInvisible();
        }
    }

    //支付方式dialog
    public void setPayDialog(View.OnClickListener onClick) {
        walletDialog = new MyWalletDialog(getContext());
        walletDialog.setPayDialog(onClick);
        walletDialog.setCanceledOnTouchOutside(false);
        walletDialog.show();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()) {
            setUserVisibleHint(true);
        }
    }


    //--------------------------------method---------------------------//

    /**
     * 懒加载
     */
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || !isFirst) {
            return;
        }
        initData();
        isFirst = false;
    }

    //--------------------------abstract method------------------------//

    /**
     * 在onActivityCreated中调用的方法，可以用来进行初始化操作。
     */
    protected abstract void initPrepare();

    /**
     * fragment被设置为不可见时调用
     */
    protected abstract void onInvisible();

    public abstract int getRootViewId();


    /**
     * 这里获取数据，刷新界面
     */
    protected abstract void initData();

    public void hideLoading() {
        try {
            if (mainDialog != null) {
                mainDialog.dismiss();
            }
        } catch (Exception e) {
            Log.e("mainDialog报错", e.getMessage());
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        ToastUtils.cancel();
    }

    public void showLoading() {
        if (mainDialog != null) {
            mainDialog.show();
        }
    }

    /**
     * 初始化加载状态View
     *
     * @param resourceView        需要被替换的view
     * @param skeletonLayoutResID 替换的view/骨架viewId
     */
    public void initLoadingView(View resourceView, int skeletonLayoutResID) {
        mLoading = Skeleton.bind(resourceView)
                .load(skeletonLayoutResID == 0 ? R.layout.mult_state_loading : skeletonLayoutResID)
                .buid();
    }

    /**
     * 加载成功
     */
    public void hideLoaingView() {
        if (mLoading != null) {
            mLoading.hide();
        }
    }

    /**
     * 加载中
     */
    public void showLoadingView() {
        if (mLoading != null) {
            mLoading.show();
        }
    }

    /**
     * 加载错误/失败
     */
    public void showErrorView() {
        if (mLoading != null) {
            View retry = mLoading.error();
            if (retry != null) {
                retry.setOnClickListener(v -> {
                    if (onRetryListener != null) {
                        onRetryListener.onClick();
                    }
                });
            }
        }
    }

    /**
     * 加载为空数据
     */
    public void showEmptyView() {
        if (mLoading != null) {
            mLoading.empty();
        }
    }

    /**
     * 加载错误/失败重试的点击事件
     *
     * @param onRetryListener
     */
    public void setOnRetryListener(OnRetryListener onRetryListener) {
        this.onRetryListener = onRetryListener;
    }

    public interface OnRetryListener {
        void onClick();
    }


    /**
     * 是否注册事件分发
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (isRegisterEventBus()) {
            if (EventBus.getDefault().isRegistered(this))
                EventBus.getDefault().unregister(this);
        }
    }

    public void forward(Fragment fragment, boolean hide) {
        forward(getId(), fragment, null, hide);
    }

    public void forward(int viewId, Fragment fragment, String name, boolean hide) {
        FragmentTransaction trans = getFragmentManager()
                .beginTransaction();
        if (hide) {
            trans.hide(this);
            trans.add(viewId, fragment);
        } else {
            trans.replace(viewId, fragment);
        }

        trans.addToBackStack(name);
        trans.commitAllowingStateLoss();
    }

    public void backward() {
        getFragmentManager().popBackStack();
    }
}
